package com.chagee.store.operation.server.utils;

import com.chagee.store.operation.common.constant.AiEvsParamsConstant;
import org.apache.commons.codec.binary.Hex;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Lee
 * @description 百度AI图片识别接口 鉴权通用工具
 * @date 2024/8/12 18:13
 */
public class GenerateBaiduAiTokenUtil {

	/**
	 * 生成请求参数 map
	 */
	public static Map<String, String> getParamsWithNodeAuth(String uri, String bodyMd5, String ak, String sk) {
		Date date = new Date();
		long curTime = date.getTime() / 1000;
		long expireTime = curTime + 5 * 60 * 1000;
		String token = hmacSha256(String.format(AiEvsParamsConstant.AUTH_PARAM_KEY_FORMAT, ak, sk, uri, expireTime, bodyMd5), sk);
		Map<String, String> reqParams = new HashMap<>();
		reqParams.put(AiEvsParamsConstant.AUTH_PARAM_KEY_USER, ak);
		reqParams.put(AiEvsParamsConstant.AUTH_PARAM_KEY_DATE, String.valueOf(expireTime));
		reqParams.put(AiEvsParamsConstant.AUTH_PARAM_KEY_MD5, bodyMd5);
		reqParams.put(AiEvsParamsConstant.AUTH_PARAM_KEY_AUTH, token);
		return reqParams;
	}

	/**
	 * 鉴权生成token
	 */
	public static String hmacSha256(String input, String secretKey) {
		return hmacSha256(input.getBytes(StandardCharsets.UTF_8), secretKey.getBytes(StandardCharsets.UTF_8));
	}

	/**
	 * 鉴权生成token
	 */
	public static String hmacSha256(byte[] input, byte[] secretKey) {
		return hmacSha256(input, 0, input.length, secretKey);
	}

	/**
	 * 鉴权生成token
	 */
	public static String hmacSha256(byte[] input, int offset, int length, byte[] secretKey) {
		return new String(Hex.encodeHex(mac(input, offset, length, new SecretKeySpec(secretKey, AiEvsParamsConstant.HMAC_SHA256))));
	}

	/**
	 * 鉴权生成token
	 */
	public static byte[] mac(byte[] input, int offset, int length, SecretKey secretKey) {
		try {
			Mac mac = Mac.getInstance(secretKey.getAlgorithm());
			mac.init(secretKey);
			mac.update(input, offset, length);
			return mac.doFinal();
		} catch (Exception ex) {
			throw new IllegalArgumentException(ex);
		}
	}

}
